package com.example.felord.oauth2_1samples.wechat;


import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest;
import org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequestEntityConverter;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * customize wechat token-uri's parameters
 * we cloud not directly extend AbstractOAuth2AuthorizationGrantRequestEntityConverter, since it is not public
 * @author zhouchang
 * @since 2022-03-31
 */
public class WechatOAuth2AuthorizationCodeGrantRequestEntityConverter
        extends OAuth2AuthorizationCodeGrantRequestEntityConverter{


    @Override
    protected MultiValueMap<String, String> createParameters(
            OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest) {

        ClientRegistration clientRegistration = authorizationCodeGrantRequest.getClientRegistration();
        String registrationId = clientRegistration.getRegistrationId();
        if(!"wechat".equals(registrationId)){
            return super.createParameters(authorizationCodeGrantRequest);
        }

        OAuth2AuthorizationExchange authorizationExchange = authorizationCodeGrantRequest.getAuthorizationExchange();
        MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
        parameters.add(OAuth2ParameterNames.GRANT_TYPE, authorizationCodeGrantRequest.getGrantType().getValue());
        parameters.add(OAuth2ParameterNames.CODE, authorizationExchange.getAuthorizationResponse().getCode());
        String redirectUri = authorizationExchange.getAuthorizationRequest().getRedirectUri();
        if (redirectUri != null) {
            parameters.add(OAuth2ParameterNames.REDIRECT_URI, redirectUri);
        }
        // replace client_id with appid ,and client_secret with secret
        parameters.add("appid",clientRegistration.getClientId());
        parameters.add("secret",clientRegistration.getClientSecret());

        return parameters;

    }

}
